from __future__ import absolute_import, division, print_function, unicode_literals

import datetime  # For datetime objects
import os.path  # To manage paths
import sys  # To find out the script name (in argv[0])

# Import the backtrader platform
import backtrader as bt

import MySQLDataFeed as mdf
import SimpleMySqlClass as smc


class TalibSma(bt.Strategy):

    params = (("period_sma20", 20), ("period_sma60", 60))

    # 打印日志
    def log(self, txt, dt=None):
        dt = dt or self.data.datetime.date(0)
        print("%s, %s" % (dt, txt))

    def __init__(self):
        # bt.talib.SMA(self.data.close, timeperiod=30, plotname="TA_SMA")
        bt.indicators.SMA(self.data, period=10)
        pass


if __name__ == "__main__":
    print("SMA:", bt.talib.MA_Type.SMA)
    print("T3:", bt.talib.MA_Type.T3)

    # Create a cerebro entity
    cerebro = bt.Cerebro()

    # Add a strategy
    cerebro.addstrategy(TalibSma)

    tableName = "t_stock_k_data"
    sql = f"select sd_date, sd_open, sd_high, sd_low, sd_close, sd_volume from {tableName}"
    # sql = f"select sd_date as date, sd_code as code, sd_open as code, sd_high as high, sd_low as low, sd_close as low, sd_volume as volume, sd_amount as amount from {tableName}"

    data = mdf.MySQLDataFeed(sql)

    # Add the Data Feed to Cerebro
    cerebro.adddata(data, name="2Line")

    # Set our desired cash start
    cerebro.broker.setcash(1000.0)

    # Add a FixedSize sizer according to the stake
    cerebro.addsizer(bt.sizers.FixedSize, stake=10)

    # Set the commission
    cerebro.broker.setcommission(commission=0.0005)

    # Print out the starting conditions
    print("Starting Portfolio Value: %.2f" % cerebro.broker.getvalue())

    # Run over everything
    cerebro.run()

    # Print out the final result
    print("Final Portfolio Value: %.2f" % cerebro.broker.getvalue())

    # Plot the result
    cerebro.plot(style="candle", barup="red", bardown="green")
